var app = getApp();
import { bindUser, getInfo, index } from '@/api/index/index';

async function loginInfo(e) {
    console.log('获取手机号回调:', e.detail);
    
    // 检查获取手机号是否成功
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        console.error('获取手机号失败:', e.detail.errMsg);
        uni.hideLoading();
        uni.showToast({
            title: '获取手机号失败，请重试',
            icon: 'none'
        });
        return;
    }
    
    uni.showLoading({
        title: '登录中...'
    });
    
    try {
        // 先获取登录code
        const loginResult = await new Promise((resolve, reject) => {
            uni.login({
                success: resolve,
                fail: reject
            });
        });
        
        console.log('登录成功，code:', loginResult.code);
        
        // 准备请求数据
        let data = {
            code: e.detail.code,
            grant_type: 'miniApp',
            scope: 'server',
            shopId: uni.getStorageSync('shopId')
        };
        
        let header = {
            Authorization: 'Basic dGVzdDp0ZXN0',
            userType: 2
        };
        
        console.log('请求数据:', data);
        console.log('请求头:', header);
        
        // 发送登录请求
        const tokenResult = await new Promise((resolve, reject) => {
            uni.request({
                url: getApp().globalData.baseUrl + '/auth/oauth/token',
                data,
                header,
                success: resolve,
                fail: reject
            });
        });
        
        console.log('获取token成功:', tokenResult);
        
        // 保存token
        uni.setStorageSync('token', tokenResult.data.access_token);
        app.globalData.token = tokenResult.data.access_token;
        
        // 获取用户信息
        const userInfoResult = await getInfo();
        console.log('获取用户信息成功:', userInfoResult);
        
        uni.setStorageSync('userInfo', userInfoResult.data);
        app.globalData.userInfo = userInfoResult.data;
        
        // 绑定用户
        await bindUser({
            code: loginResult.code,
            userInfo: userInfoResult.data
        });
        
        console.log('用户绑定成功');
        
        uni.hideLoading();
        uni.showToast({
            title: '登录成功',
            icon: 'success'
        });
        
        // 返回上一页
        setTimeout(() => {
            uni.navigateBack({
                delta: 1
            });
        }, 1500);
        
    } catch (error) {
        console.error('登录失败:', error);
        uni.hideLoading();
        uni.showToast({
            title: error.msg || '登录失败，请重试',
            icon: 'none'
        });
    }
}

module.exports = {
    loginInfo
};
